import axios from 'axios'
import { message } from 'antd'

import { customHistory } from './history'

import store from '@/store'
import { logout } from '@/store/actions'

const baseURL =
  process.env.NODE_ENV === 'production' ? process.env.REACT_APP_URL : '/api'

const http = axios.create({
  // baseURL: 'http://geek.itheima.net/v1_0',
  // baseURL: 'http://toutiao.itheima.net/v1_0',
  // baseURL: '/api',
  baseURL,
  timeout: 6000,
})

http.interceptors.request.use((config) => {
  const { login: token } = store.getState()

  if (!config.url.startsWith('/authorizations')) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

http.interceptors.response.use(undefined, (err) => {
  if (!err.response) {
    message.error('网络繁忙，请稍后再试！')
  } else if (err.response.status === 401) {
    // 说token过期了
    message.error('登录超时了，请重新登录！', 1.5, () => {
      store.dispatch(logout())
      customHistory.replace('/login', {
        from: customHistory.location.pathname,
      })
    })
  }
  return Promise.reject(err)
})

export { http }
